package com.wc.alorithm_luogu.P1616;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @Author congge
 * @Date 2023/9/30 21:13
 * @description 疯狂的采药
 * 背包问题的升级版
 * https://www.luogu.com.cn/problem/P1616
 */
public class Main {
    public static void main(String[] args) {
        Input scan = new Input();
        int medicineTime = scan.nextInt();
        int n = scan.nextInt();

        Medicine[] medicines = new Medicine[n];
        for (int i = 0; i < n; i++) {
            Medicine medicine = new Medicine();
            medicines[i] = medicine;
            medicine.time = scan.nextInt();
            medicine.value = scan.nextInt();
        }
        Comparator<Medicine> comparator = new Comparator<Medicine>() {
            @Override
            public int compare(Medicine o1, Medicine o2) {
                return o1.time - o2.time;
            }
        };

        Arrays.sort(medicines, comparator);
        long[][] dp = new long[n][medicineTime + 1];

        for (int i = medicines[0].time; i <= medicineTime; i++) {
            dp[0][i] = (long) i / medicines[0].time * medicines[0].value;
        }

        for (int i = 1; i < n; i++) {
            for (int j = 1; j <= medicineTime; j++) {
                if (j >= medicines[i].time) {
                    int number = j / medicines[i].time;
                    /**
                     * 这里得注意一下，每次不相同,得用最大的一次比较
                     */
                    long max = 0;
                    for (int k = 1; k <= number; k++) {
                        max = Math.max(max, dp[i - 1][j - k * medicines[i].time] + (long) k * medicines[i].value);
                    }
                    dp[i][j] = Math.max(dp[i - 1][j], max);
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }

        System.out.println(dp[n - 1][medicineTime]);
    }


    static class Medicine {
        int value;
        int time;
    }

    static class Input {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

        public int nextInt() {
            try {
                in.nextToken();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return (int) in.nval;
        }
    }
}
